package databaseHelper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * A enum providing the data source.
 * 
 * Follows the Singleton pattern, to avoid multiple creation of the connection
 * 
 * @author Rupert
 *
 */
public enum DataSource {
	
	/**
	 * Singleton pattern Instance
	 */
	INSTANCE;
	
	/**
	 * Information for database connection
	 */
	private static final String url = "jdbc:mysql://localhost:3306/examDB";
	private static final String user = "examDBUser";
	private static final String pwd = "test1";

	private Connection conn = null;

	static {
		try {
			/**
			 * driver to be used
			 */
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private DataSource() {
		
	}
	
	
	/**
	 * get SQL statement for queries
	 * @return
	 * @throws SQLException
	 */
	public Statement getStatement() throws SQLException {
		Statement stmt = null;
		// get connection
		conn = DriverManager.getConnection(url,user,pwd);
		
		stmt = conn.createStatement();
		return stmt;
	}
	
	
	/**
	 * close connection when not needed anymore
	 */
	public void close() {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}